package org.bbelovic.devel.snake;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class performs whole drawing in Snake game. It is the role of game controller to change
 * and modify state of the game and drawing panel then draws this modified state.
 */
public class DrawPanel extends JPanel implements ActionListener {

    private static final long serialVersionUID = 3196761162581373649L;
    /** default delay between two timer ticks */
    private static final int TIMER_DELAY = 200;
    /** logging facility */
    private static final Logger LOGGER = LoggerFactory.getLogger(DrawPanel.class);
    /** timer which performs delay between animation update */
    private final Timer timer;

    /** game controller which modifies state of the game */
    private final DefaultGameController controller;

    /**
     * Creates new instance.
     * @param controller {@link DefaultGameController} which controls whole game.
     */
    public DrawPanel(final DefaultGameController controller) {
        this.controller = controller;
        this.timer = new Timer(TIMER_DELAY, this);
        timer.start();
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public void paintComponent(final Graphics g) {
        clearDrawPanel(g);
        controller.paintGameScene(g);
        LOGGER.info(controller.getSnake().toString());
    }

    /**
     * {@inheritDoc}
     */
    public void actionPerformed(ActionEvent e) {
        controller.moveInDirection();
        if (controller.isInBorderCollision()) {
            LOGGER.info("Corner colision, game is over");
            timer.stop();
        }
        repaint();
    }

    /**
     * Sets new direction for snake.
     * @param direction in which snake will be moving
     */
    void setDirection(final Direction direction) {
        controller.setMoveDirection(direction);
    }

    /**
     * Stops animation timer and thus the whole game.
     */
    void timerStop() {
        timer.stop();
    }

    /**
     * Clear this panel by setting drawing white rectangle over whole panel
     * @param g {@link Graphics} instance used for clearing panel screen
     */
    private void clearDrawPanel(final Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, getWidth(), getHeight());
    }
}
